package dao.impl;

import dao.BookDao;
import entity.Book;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import util.DbUtils;

import java.sql.SQLException;
import java.util.List;

/**
 * User: key
 * ClassName:BookDaoImpl
 * Date: 2023/5/5
 * Time: 18:50
 * description:
 */
public class BookDaoImpl implements BookDao {
    private QueryRunner qr = new QueryRunner(DbUtils.getDataSource());
    @Override
    public int addBook(Book b) throws SQLException {
        return qr.update("insert into book values (default,?,?,?,?,?,?,?)",
                b.getName(),
                b.getAuthor(),
                b.getPublish(),
                b.getPublishDate(),
                b.getPage(),
                b.getPrice(),
                b.getContent());
    }

    @Override
    public Book getOneById(int id) throws SQLException {
        return qr.query("select * from book where id = ?",
                new BeanHandler<>(Book.class),id);
    }

    @Override
    public int delBook(int id) throws SQLException {
        return qr.update("delete from book where id = ?",id);
    }

    @Override
    public Long getCount() throws SQLException {
        return qr.query("select count(1) from book",new ScalarHandler<>());
    }

    @Override
    public List<Book> getByPage(int pageNum, int pageSize) throws SQLException {
        return qr.query("select * from book limit ?,?",new BeanListHandler<>(Book.class),
                pageNum,
                pageSize);
    }

    @Override
    public List<Book> getAll() throws SQLException {
        return qr.query("select * from book",new BeanListHandler<>(Book.class));
    }
}
